<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="90px">
      <el-form-item label="昵称" prop="nicknameOrUsername">
        <el-input v-model="queryParams.nicknameOrUsername" placeholder="请输入" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <page-table :url="url.list" ref="table" :tableForm="queryParams" :columns="columns">
      <template #action="scope">
        <el-tooltip content="修改" placement="top">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
        </el-tooltip>
        <el-tooltip content="设置数据权限" placement="top">
          <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(scope.row)"></el-button>
        </el-tooltip>
      </template>
      <template #status="scope">
        <el-switch v-model="scope.row.status" v-if="scope.row.status != undefined" :active-value="1" :inactive-value="0"
          @change="handleDelete(scope.row, scope.row.status)"></el-switch>
      </template>
    </page-table>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="登录手机号" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" show-password v-model="form.pass" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="确认密码" prop="passCo">
          <el-input type="password" show-password v-model="form.passCo" :disabled="!form.pass" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配用户数据权限对话框 -->
    <el-dialog :title="title" v-model="openDataScope" width="500px" append-to-body>
      <el-form  ref="roleRefs" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户权限" prop="permissionType">
          <matic-select v-model:value="form.permissionType" :options="dataScopeOptions"
            :objMap="{ value: 'value', label: 'label', children: 'children' }" placeholder="请选择" />
        </el-form-item>
        <el-form-item v-show="form.permissionType == '2'" label="客户数据" prop="customers">
          <matic-select v-model:value="form.customers" multiple :url="`customer/getAllList/forManager`"
            :objMap="{ value: 'id', label: 'title' }" placeholder="请选择" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import Schema from 'async-validator';
import request from '@/utils/request'
const router = useRouter();
import { Encrypt, Decrypt } from "@/utils/AES256";
const { proxy } = getCurrentInstance();

const url = ref({
  list: 'users/getPage/forManager',
  fine: 'users/getOne/forManager',
  delete: 'users/disableOrUse/forManager',
  add: 'users/save/forManager',
  edit: 'users/save/forManager'
});

const Customerurl = ref({
  fine: 'users/getCustomerDataAuth/forManager',
  edit: 'users/saveCustomerDataAuth/forManager'
});

const open = ref(false);
const title = ref("");
const openDataScope = ref(false);
const table = ref(null);

const columns = ref([{
  key: 'nickname',
  title: '昵称',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'customerDataAuthUsersCount',
  title: '客户权限数量',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'permissionTypeStr',
  title: '客户权限',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'username',
  title: '账号',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'tel',
  title: '登录手机号',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'email',
  title: '邮箱',
  ellipsis: true,
  tooltip: true,
},
{
  key: 'status',
  title: '状态',
  align: 'center',
  width: 150,
  slots: {
    customKey: 'status',
  },
},
{
  key: 'createTime',
  title: '日期',
  ellipsis: true,
  tooltip: true,
},
{
  title: '操作',
  key: 'action',
  slots: {
    customKey: 'action',
  },
  align: 'center',
  fixed: 'right',
  width: 150
}]);

const handleDelete = (row, status) => {
  const id = row.id
  let text = row.status == "1" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.nickname + '"吗?').then(function () {
    return request.get(url.value.delete, { params: { id } });
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
}

/** 数据范围选项*/
const dataScopeOptions = ref([
  { value: 1, label: "全部权限" },
  { value: 2, label: "个别权限" },
]);

//新密码与重复密码不一致，一定写在data里但不是return里
let repeatValidate = (rule, value, callback) => {
  if (value !== form.value.pass) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
//正则校验主要是这部分：/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,16}$
//其中特殊字符包括：._~!@#$^&*  （比较常见）
let newValValidate = (rule, value, callback) => {
  if (/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,16}$/g.test(value)) {
    callback()
  } else {
    callback(new Error('请输入包含英文字母大小写、数字和特殊符号的 8-16 位组合'))
  }
}

// 手机号
const tel_phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

const data = reactive({
  form: {},
  queryParams: {},
  rules: {
    nickname: [{ required: true, message: "昵称不能为空", trigger: "blur" }],
    username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
    tel: [{ required: true, pattern: tel_phone, message: '请输入正确的手机号', trigger: "blur" }],
    pass: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        min: 8,
        max: 16,
        message: '长度应在 8 到 16 个字符',
        trigger: 'blur'
      },
      { validator: newValValidate, trigger: 'blur' }
    ],
    passCo: [
      { required: true, message: '请再输入一遍新密码', trigger: 'blur' },
      { validator: repeatValidate, trigger: 'blur' }
    ],
    email: [{ type: 'email', required: true, message: "邮箱格式错误", trigger: "blur" }],
    permissionType: [{ required: true, message: "客户权限不能为空", trigger: "blur" }],
    customers: [{
      type: "array", min: 1, required: true, message: "客户数据不能为空", trigger: "blur"
    }]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
  table.value.onload();
}
/** 搜索按钮操作 */
function handleQuery() {
  table.value.init();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}


/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    nickname: '',
    username: '',
    email: '',
    tel: '',
    pass: '',
    passCo: '',
    permissionType: '',
    customers: [],
  };
  proxy.resetForm("roleRef");
}
/** 添加用户 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户";
}
/** 修改用户 */
function handleUpdate(row) {
  reset();
  const id = row.id
  request.get(url.value.fine, { params: { id } }).then(response => {
    form.value = response.result;
    open.value = true;
    title.value = "修改用户";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      let from = { ...form.value };
      from.pass = Encrypt(form.value.pass)
      from.passCo = Encrypt(form.value.passCo)
      from.tel = Encrypt(form.value.tel)
      from.email = Encrypt(form.value.email)
      if (form.value.id != undefined) {
        request.post(url.value.edit, from).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        request.post(url.value.add, from).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 分配数据权限操作 */
function handleDataScope(row) {
  reset();
  request.get(Customerurl.value.fine, { params: { id: row.id } }).then(response => {
    form.value = {
      ...response.result,
      customers: response.result.customersStr
    };
    openDataScope.value = true;
    title.value = "分配数据权限";
  });
}
/** 提交按钮（数据权限） */
function submitDataScope() {
  proxy.$refs["roleRefs"].validate(valid => {
    if (valid) {
      if (form.value.usersId) {
        request.post(Customerurl.value.edit, form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openDataScope.value = false;
          getList();
        });
      }
    }
  })
}
/** 取消按钮（数据权限）*/
function cancelDataScope() {
  openDataScope.value = false;
  reset();
}

</script>
